package jcc.example.com.broweimg.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import jcc.example.com.broweimg.R;

/**
 * 图片黑白效果
 */
public class BlackOrWhiteView  extends View {

    public BlackOrWhiteView(Context context) {
        super(context);
    }

    public BlackOrWhiteView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public BlackOrWhiteView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //需要关闭硬件加速(没有关闭则没效果)
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_iamge1);
        canvas.drawBitmap(bitmap,null,new RectF(0,0,400,400*bitmap.getHeight()/bitmap.getWidth()),paint);
        canvas.translate(400,0);
        /**
         * 去色原理：只要把RGB三通道的色彩信息设置成一样，即：R=G=B
         * 那么图像就变成了灰色，并且，为了保证图像亮度不变，
         * 同一个通道中的R+G+B=1；如0.213+0.175+0.072 =1;
         * RGB=0.213,0.175,0.072
         * 三个数字是根据色彩光波频率及色彩心理学计算出来的
         */
        ColorMatrix matrix = new ColorMatrix(new float[]{
                0.213f, 0.715f, 0.072f, 0,0,
                0.213f, 0.715f, 0.072f, 0,0,
                0.213f, 0.715f, 0.072f, 0,0,
                0,      0,           0, 1,0,
        });
        //设置颜色过滤器
        paint.setColorFilter(new ColorMatrixColorFilter(matrix));
        canvas.drawBitmap(bitmap,null,new RectF(0,0,400,400*bitmap.getHeight()/bitmap.getWidth()),paint);
    }

}
